package com.example.webview.mainprocess;

import android.os.RemoteException;

import com.example.webview.IMainProcessToWebViewProcessInterface;
import com.example.webview.IWebViewProcessToMainProcessInterface;
import com.example.webview.webviewprocess.command.Command;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * Created by ymz0427 on 2021/10/2
 */
public class MainProcessCommandManager extends IWebViewProcessToMainProcessInterface.Stub {

    private static final class InstanceHolder {
        static final MainProcessCommandManager instance = new MainProcessCommandManager();
    }

    public static MainProcessCommandManager getInstance() {
        return InstanceHolder.instance;
    }

    private MainProcessCommandManager() {
        ServiceLoader<Command> load = ServiceLoader.load(Command.class);
        for (Command command : load) {
            if (!map.containsKey(command.getName())) {
                map.put(command.getName(), command);
            }
        }
    }

    private final Map<String, Command> map = new HashMap<>();



    @Override
    public void handleCommand(String command, String params) throws RemoteException {
        try {
            Command tmp = map.get(command);
            if (tmp != null) {
                tmp.execute(params);
            } else {
                throw new RemoteException("没有找到对应的Command");
            }
        } catch (Exception e) {
            throw new RemoteException(e.getMessage());
        }
    }

    @Override
    public void handleCommandWithCallback(String command, String params,
                                          IMainProcessToWebViewProcessInterface callback) throws RemoteException {
        try {
            Command tmp = map.get(command);
            if (tmp != null) {
                tmp.execute(params, callback);
            } else {
                throw new RemoteException("没有找到对应的Command");
            }
        } catch (Exception e) {
            throw new RemoteException(e.getMessage());
        }
    }
}
